package com.thx.information.action;

import com.thx.common.struts2.CurdAction;
import com.thx.common.web.ActionResult;
import com.thx.information.model.InfoColumn;
import com.thx.information.service.ColumnService;
import com.thx.log.LogUtil;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.InterceptorRef;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.ParentPackage;
import org.apache.struts2.convention.annotation.Result;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import java.util.Date;

@ParentPackage(value = "gloab-package")
@Namespace(value = "/information")
@Action(value = "column",
    results = {@Result(name = "column", location = "/pages/information/column.jsp"),
        @Result(name = "tree", location = "/pages/information/column/tree.jsp"),
        @Result(name = "list", location = "/pages/information/column/list.jsp"),
        @Result(name = "input", location = "/pages/information/column/input.jsp"),
        @Result(name = "json", type = "json", params = {"root", "result"})},
    interceptorRefs = {@InterceptorRef(value = "topDtStack"),
        @InterceptorRef(value = "pageInterceptor", params = {"includeMethods", "list"}),})
@Controller
@Scope("prototype")
public class ColumnAction extends CurdAction<InfoColumn> {

  private static final long serialVersionUID = 1L;
  private static final Logger logger = LoggerFactory.getLogger(ColumnAction.class);

  @Autowired
  private ColumnService service;

  private String ids;
  private String treeNodes;
  private String pid;
  private String searchName;
  private String ifSee;

  // 测试数据
  private Long enterpriseId = 181L;
  private Long personnelId = 1048L;
  private String personnelName = "管理员";
  private Long depId = 1L;
  private Long role = 1L;
  private Boolean ifAdmin = true;


  // /**
  // * 删除栏目 建立日期 : Apr 19, 2014 5:00:24 PM<br>
  // * 作者 : 王阿敏<br>
  // *
  // * @param stringIds
  // */
  // public String deleteColumnById() {
  // logger.debug("<进入>:deleteColumnById方法");
  // Personnel p = (Personnel) getSession().getAttribute("personnel");
  // Long enterpriseId = (Long) getSession().getAttribute("enterpriseId");
  // String[] stringIdss = stringIds.split(",");
  // havinginformation = "";
  // for (int i = 0; i < stringIdss.length; i++) {
  // Long columnId = Long.valueOf(stringIdss[i]);
  // InfoColumn column = columnService.get(columnId);
  // Information view = new Information();
  // view.setEnterpriseId(enterpriseId);
  // view.setColumnId(columnId);
  // List<Information> infoList = infomationService.queryAll(view, 0, 1);
  //
  // if (infoList == null || infoList.size() == 0) {
  // columnService.delete(columnId);
  // infomationService.deleteByColumnId(columnId);
  // } else {
  // havinginformation += column.getColumnName() + ",";
  // }
  // try {
  // Print2databaselog.print(p, OAConstant.MODULE_COLUMN, OAConstant.ACTION_DELETE,
  // p.getName() + ",删除栏目,栏目名称:" + column.getColumnName(), new Date() + "",
  // AppContext.getProperties("oabiz"));
  // } catch (UnknownHostException e) {
  // logger.error("<错误>:后台删除栏目出错" + e);
  // }
  // }
  // return "delete";
  // }

  // /**
  // * @创建日期 2013-4-28<br>
  // * @作者: wangamin <br>
  // * @描述: 根通栏目名称验证栏目是否存在<br>
  // */
  // public void queryByName() {
  // logger.debug("<进入>:queryByName方法");
  // String json = "";
  // int msg = 0;
  // try {
  // if (StringUtils.isNotBlank(entity.getColumnName())) {
  // msg = columnService.queryByName(entity);
  // }
  // json = com.alibaba.fastjson.JSON.toJSONString(msg);
  // } catch (Exception e) {
  // logger.error("<错误>:验证通信录分类验证错误", e);
  // json = "{result:'error'}";
  // }
  // try {
  // writeJson(json);
  // } catch (IOException e) {
  // logger.error("<错误>:验证通信录分类验证错误", e);
  // }
  // }
  //
  // /**
  // * 把新的对象中有值的成员变量的值，赋给旧的对象中
  // */
  // private static void setNewValue(Object orig, Object dest) throws Exception {
  //
  // Field[] destFields = dest.getClass().getDeclaredFields();
  // for (Field field : destFields) {
  // field.setAccessible(true);
  // Object value = field.get(dest);
  // if (value == null)
  // continue;
  // if (value instanceof String && StringUtils.isBlank((String) value))
  // continue;
  // Field origField = orig.getClass().getDeclaredField(field.getName());
  // origField.setAccessible(true);
  // origField.set(orig, value);
  // }
  // }

  // /**
  // * 修改栏目的orderno
  // */
  // public void saveOrder() {
  // logger.debug("<进入>:saveOrder方法");
  // Personnel p = (Personnel) getSession().getAttribute("personnel");
  // HttpServletRequest request = ServletActionContext.getRequest();
  // String[] columnId = request.getParameterValues("columnId");
  // String[] columnOrder = request.getParameterValues("columnOrder");
  // if (columnId != null && columnOrder != null) {
  // for (int i = 0; i < columnId.length; i++) {
  // ;
  // InfoColumn column = new InfoColumn();
  // column = columnService.get(Long.parseLong(columnId[i]));
  // if (column != null) {
  // if (columnOrder[i] != null && !"".equals(columnOrder[i])) {
  // column.setColumnOrder(Long.parseLong(columnOrder[i]));
  // } else {
  // column.setColumnOrder(null);
  // }
  // columnService.save(column);
  // }
  // }
  // }
  // try {
  // Print2databaselog.print(p, OAConstant.MODULE_COLUMN, OAConstant.ACTION_UPDATE,
  // p.getName() + "保存排序", new Date() + "", AppContext.getProperties("oabiz"));
  // } catch (UnknownHostException e) {
  // logger.error("<错误>:后台查询栏目列表出错" + e);
  // }
  // }


  // /**
  // * 所有栏目的json数组
  // *
  // * @author 冯晋首
  // * @date 2014-7-17 下午6:06:46
  // */
  // public void getColumnJsonArray() {
  // logger.debug("<进入>:getColumnJsonArray方法");
  // HttpSession session = getSession();
  // Long enterpriseId = (Long) session.getAttribute("enterpriseId");
  // columns = new ArrayList<InfoColumn>();
  // List<InfoColumn> finialColumns = new ArrayList<InfoColumn>();
  // columns = columnService.queryAll(enterpriseId, "");
  // for (int i = 0; i < columns.size(); i++) {
  // if (!(OAConstant.IS_COMMON).equals(columns.get(i).getIsCommon())) {
  // finialColumns.add(columns.get(i));
  // }
  // }
  // JSONArray json = JSONArray.fromObject(finialColumns);
  // HttpServletResponse response = ServletActionContext.getResponse();
  // response.setContentType("text/plain;charset=UTF-8");
  // response.setCharacterEncoding("utf-8");
  // response.setHeader("Charset", "utf-8");
  // response.setHeader("Cache-Control", "no-cache");
  // try {
  // if (columns.size() != 0) {
  // response.getWriter().write(json.toString());
  // } else {
  // response.getWriter().write("");
  // }
  // } catch (IOException e) {
  // logger.error("<错误>:获取所有栏目的json数组出错" + e);
  // }
  // }

  protected void doList() {
    logger.debug("<进入>:doList方法  显示栏目");
    logger.debug("<入参>:searchName={}", searchName);
    try {
      String isPublic = StringUtils.isNotBlank(ifSee) ? "1" : "";
      list = service.findByEnterpriseAttributes(enterpriseId, isPublic, searchName);
      logger.debug("<出参>查询结果{}：", list);
    } catch (Exception e) {
      logger.error("<错误>:查询异常");
    }
  }

  protected void doView() {}

  /**
   * 新增、修改显示页面.
   * 
   */
  public String input() {
    logger.debug("<进入>:栏目修改/新增跳转方法");
    logger.info("<入参>:id={}", id);
    try {
      if (StringUtils.isNotBlank(id)) {
        entity = service.get(Long.parseLong(id));
      }
      logger.debug("<出参>查询结果{}：", entity);
    } catch (Exception e) {
      logger.error("<错误>:查询异常");
    }
    return "input";
  }

  /**
   * 新增修改方法.
   */
  public void doSave() {
    try {
      if (StringUtils.isBlank(id)) {
        logger.debug("<进入>:栏目管理新增方法");
        logger.info("<入参>:新增数据={}", entity);
        InfoColumn entityd = new InfoColumn();
        BeanUtils.copyProperties(entity, entityd);
        entityd.setCreateUser(personnelName);
        entityd.setEnterpriseId(enterpriseId);
        entityd.setCreateUser("" + personnelId);
        entityd.setCreateTime(new Date());
        service.save(entityd);
        setResult(SUCCESS, "新增成功！");
        LogUtil.log("分类管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "新增信息");
      } else {
        logger.debug("<进入>:栏目管理修改方法");
        logger.info("<入参>:修改栏目id={}", entity);
        InfoColumn entityd = service.get(Long.parseLong(id));
        BeanUtils.copyProperties(entity, entityd, new String[] {"columnId", "enterpriseId",
            "createTime", "updateUser", "updateTime", "createUser"});
        entityd.setUpdateUser(personnelName);
        entityd.setUpdateTime(new Date());
        entityd.setUpdateUser("" + personnelId);
        service.update(entityd);
        setResult(SUCCESS, "修改成功！");
        LogUtil.log("栏目管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_SUCCESS, "修改信息");
      }
    } catch (Exception e) {
      if (StringUtils.isNotBlank(id)) {
        LogUtil.log("栏目管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "修改信息");
        logger.error("<错误>:修改异常{}", e);
      } else {
        LogUtil.log("栏目管理", LogUtil.ACTION_UPDATE, LogUtil.RESULT_FAIL, "新增信息");
        logger.error("<错误>:新增异常{}", e);
      }
    }
  }

  protected void doDelete() {
    logger.debug("<进入>:删除栏目信息方法");
    try {
      if (StringUtils.isNotBlank(id)) {
        logger.debug("<入参>:栏目信息数据id={}", id);
        service.delete(NumberUtils.toLong(id));
        setResult(ActionResult.SUCCESS, "删除成功！");
        LogUtil.log("栏目信息管理", LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "删除栏目信息");
      } else {
        setResult(ActionResult.FAIL, "服务器异常！");
      }
    } catch (Exception e) {
      logger.error("<错误>:删除异常{}", e);
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 批量删除信息.
   */
  protected void doDelMulti() {
    logger.debug("<进入>:批量删除栏目信息方法");
    try {
      if (ids != null && ids.split(",").length > 0) {
        logger.debug("<入参>:批量删除栏目信息id={}", ids);
        for (String del : ids.split(",")) {
          service.delete(NumberUtils.toLong(del));
        }
        setResult(ActionResult.SUCCESS, "批量删除成功！");
        LogUtil.log("栏目信息管理", LogUtil.ACTION_DELETE, LogUtil.RESULT_SUCCESS, "批量删除信息");
      } else {
        setResult(ActionResult.FAIL, "服务器异常！");
      }
    } catch (Exception e) {
      logger.error("<错误>:批量删除异常{}", e);
      setResult(ActionResult.FAIL, "服务器异常！");
    }
  }

  /**
   * 栏目名称是否存在核对方法.
   */
  public void checkName() {
    logger.debug("<进入>:栏目信息验证方法");
    try {
      logger.info("<入参>:栏目信息名称={}", entity.getColumnName());
      boolean exits = service.queryByName(entity.getColumnName()) != 0 ? true : false;
      treeNodes = com.alibaba.fastjson.JSON.toJSONString(exits);
      setResult(SUCCESS, "查询成功！");
      logger.info("<出参>:栏目信息名称checkJson={}", treeNodes);
      writeJson(treeNodes);
    } catch (Exception e) {
      logger.error("<错误>:验证异常{}", e);
    }
  }


  /**
   * 跳转到栏目管理页面.
   * 
   * @return
   */
  public String column() {
    logger.debug("<进入>:column方法 跳转栏目管理");
    return "column";
  }

  /**
   * 分类左树页面.
   * 
   */
  public String tree() {
    logger.debug("<进入>:tree方法");
    this.showColumn();
    return "tree";
  }
  
  /**
   * 显示左侧分类.
   * 
   * @return
   */
  public void showColumn() {
    logger.debug("<进入>:showColumn方法");
    try {
      Boolean displayAll = StringUtils.isNotBlank(ifSee) ? false : true;
      list = service.queryAll(enterpriseId, displayAll);
      treeNodes = com.alibaba.fastjson.JSON.toJSONString(list);
      writeJson(treeNodes);
      setResult(SUCCESS, "查询成功！");
    } catch (Exception e) {
      logger.error("<错误>:查询栏目信息异常", e);
    }
  }

  public String getIds() {
    return ids;
  }

  public void setIds(String ids) {
    this.ids = ids;
  }

  public String getTreeNodes() {
    return treeNodes;
  }

  public void setTreeNodes(String treeNodes) {
    this.treeNodes = treeNodes;
  }

  public String getPid() {
    return pid;
  }

  public void setPid(String pid) {
    this.pid = pid;
  }

  public String getSearchName() {
    return searchName;
  }

  public void setSearchName(String searchName) {
    this.searchName = searchName;
  }



}
